/****************************************************************************/
/* NAME:           tools.c                                                  */
/* PURPOSE:        Leds pwm management                                      */
/* CREATED_BY:     Vyx                                                      */
/* CREATION_DATE:  30/05/2013                                               */
/************************************** (C) Copyright 2013 AquaLink *********/

#include "tools.h"
#include "stdlib.h"

/**
  * @brief  Curve interpolation
  * @param  none
  * @retval None
  */
uint32_t TOOL_Interpolation(uint32_t *TableRefInput,
                            uint32_t *TableRefOutput,
                            uint8_t   TableSize,
                            uint32_t  ValueToInterpol)
{
    uint8_t  Index;             /* index to find the segment */
    uint32_t InterpolatedValue; /* Result of the conversion */

    /* find the index on the table*/
    for (Index=0;
        (ValueToInterpol > TableRefInput[Index]) && (Index < (TableSize-1));
         Index++);

      /* calculation of the interpolated value */
      if (((Index  == (TableSize-1))&&(ValueToInterpol >= TableRefInput[Index]))
         ||(Index==0))
      {
          /* if Output value = Min or Max value */

          InterpolatedValue = TableRefOutput[Index];
      }
      else
      /*                                       (Output[Index]-Output[Index-1])      */
      /*    Result := (Value - Input[Index-1])*-------------------------------      */
      /*                                       (Input[Index]-Input[Index-1])        */
      /*              + Output[index-1]                                             */
      {
          if (TableRefOutput[Index] > TableRefOutput[Index-1])
          {
              InterpolatedValue = (TableRefOutput[Index-1] +
                                   (((unsigned long)(ValueToInterpol - TableRefInput[Index-1]) *
                                     (unsigned long)(TableRefOutput[Index] - TableRefOutput[Index-1])) /
                                    (TableRefInput[Index] - TableRefInput[Index-1])));
          }
          else
          {
              InterpolatedValue = (TableRefOutput[Index-1] -
                                   (((unsigned long)(ValueToInterpol - TableRefInput[Index-1]) *
                                     (unsigned long)(TableRefOutput[Index-1] - TableRefOutput[Index])) /
                                    (TableRefInput[Index] - TableRefInput[Index-1])));
      }
  }

  /* return the calculated value */
  return (InterpolatedValue);
}

/**
  * @brief  To get a random number between two threshold.
  * @param  min : low threshold; max : top threshold
  * @retval Random number
  */
uint32_t TOOL_rand_min_max(uint32_t min, uint32_t max)
{
    srand(RTC_GetCounter());
    return ((rand()%(max+1-min)+min));
}
